package com.ysstech.reportworld.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.cache.RedisCacheManager;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.StringUtil;
import com.ysstech.reportworld.entity.*;
import com.ysstech.reportworld.enums.ReportWorldEnum;
import com.ysstech.reportworld.enums.ReportWorldStatusEnum;
import com.ysstech.reportworld.mapper.DatabaseConfigMapper;
import com.ysstech.reportworld.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2022-12-28
 */
@Slf4j
@Service
public class DatabaseConfigServiceImpl extends ServiceImpl<DatabaseConfigMapper, DatabaseConfig> implements DatabaseConfigService {
    @Autowired
    private DatabaseConfigMapper databaseConfigMapper;
    @Autowired
    public DemandBugInfoService demandBugInfoService;
    @Autowired
    public TableDetailService tableDetailService;
    @Autowired
    public TableService tableService;
    @Autowired
    protected RedisCacheManager redisCacheManager;

    /**
     * 通过code获取对应的配置信息
     *
     * @param code
     * @return
     * @throws Exception
     */
    public DatabaseConfig selectDatabaseConfig(String code) throws Exception {
        if (StringUtils.isBlank(code)) {
            throw new BusinessException("获取基础数据配置信息失败！");
        }
        DatabaseConfig config = new DatabaseConfig();
        config.setCode(code);
        List<DatabaseConfig> list = databaseConfigMapper.selectDatabaseConfig(config);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 获取所有配置信息
     *
     * @return
     * @throws Exception
     */
    public List<DatabaseConfig> selectListDatabaseConfig() throws Exception {
        DatabaseConfig configquery = new DatabaseConfig();
        configquery.setStatus(ReportWorldStatusEnum.REPORT_NORMAL.getCode());
        List<DatabaseConfig> list = databaseConfigMapper.selectDatabaseConfig(configquery);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return list;
    }

    /**
     * 基础数据配置管理页面的数据处理
     *
     * @param code
     * @return
     * @throws Exception
     */
    public Map<String, Object> dataBaseManager(String code) throws Exception {
        Map<String, Object> map = new HashMap<>();
        try {
            // 获取基础数据表的字段信息
            if (StringUtils.isBlank(code)) {
                throw new BusinessException("没有获取到对应的基础数据编码信息，请稍后重试！");
            }
            QueryWrapper<Table> wrapper = new QueryWrapper<>();
            wrapper.eq("NAME", code.toUpperCase().replace("RW_DB_", ""));
            Table table = tableService.getOne(wrapper);
            if (null == table || StringUtils.isBlank(table.getId())) {
                throw new BusinessException("获取基础数据表信息失败，请稍后重试！");
            }
            QueryWrapper<TableDetail> wrapperDetail = new QueryWrapper<>();
            wrapperDetail.eq("TABLE_ID", table.getId());
            List<TableDetail> listDetail = tableDetailService.list(wrapperDetail);
            // 获取库里所有字段
            if (CollectionUtils.isEmpty(listDetail)) {
                throw new BusinessException("获取基础配置表信息失败，请稍后重试！");
            }
            List<Dicvalue> list = new ArrayList<>();
            for (TableDetail detail : listDetail) {
                if (null == detail) {
                    continue;
                }
                Dicvalue dicvalue = new Dicvalue();
                dicvalue.setValue(detail.getColumnName());
                if (StringUtils.isBlank(detail.getColumnChineseName())) { // 没有中文注释用字段名称
                    dicvalue.setShowmsg(detail.getColumnName());
                    list.add(dicvalue);
                    continue;
                }
                if (detail.getColumnChineseName().indexOf(",") > -1) { //中文注释中有英文逗号，下拉框显示有有问题
                    dicvalue.setShowmsg(detail.getColumnName().replaceAll(",", "，"));
                    list.add(dicvalue);
                    continue;
                }
                dicvalue.setShowmsg(detail.getColumnChineseName());
                list.add(dicvalue);
                continue;
            }
            // 如果基础数据表区分了数据库类型 添加一个字段
            DatabaseConfig databaseConfig = this.selectDatabaseConfig(code);
            if (null != databaseConfig && 1 == databaseConfig.getDataType()) {
                Dicvalue dicvalue = new Dicvalue();
                dicvalue.setValue("RW_DB_DATABASE_TYPE");
                dicvalue.setShowmsg("数据库类型");
                list.add(dicvalue);
            }
            map.put("list", list);
            List<Dicvalue> orderColumnList = new ArrayList<>();
            List<Dicvalue> selectColumnList = new ArrayList<>();
            for (Dicvalue dicvalue : list) {
                if (null == dicvalue) {
                    continue;
                }
                Dicvalue dicvalueOrder = new Dicvalue();
                dicvalueOrder.setValue(dicvalue.getValue() + "【ASC】");
                dicvalueOrder.setShowmsg(dicvalue.getShowmsg() + "【ASC】");
                orderColumnList.add(dicvalueOrder);
                Dicvalue dicvalueOrderNew = new Dicvalue();
                dicvalueOrderNew.setValue(dicvalue.getValue() + "【DESC】");
                dicvalueOrderNew.setShowmsg(dicvalue.getShowmsg() + "【DESC】");
                orderColumnList.add(dicvalueOrderNew);
                Dicvalue dicvalueSelect = new Dicvalue();
                dicvalueSelect.setValue(dicvalue.getValue() + "【=】");
                dicvalueSelect.setShowmsg(dicvalue.getShowmsg() + "【=】");
                selectColumnList.add(dicvalueSelect);
                Dicvalue dicvalueSelectNew = new Dicvalue();
                dicvalueSelectNew.setValue(dicvalue.getValue() + "【LIKE】");
                dicvalueSelectNew.setShowmsg(dicvalue.getShowmsg() + "【LIKE】");
                selectColumnList.add(dicvalueSelectNew);
            }
            map.put("orderColumnList", orderColumnList);
            map.put("selectColumnList", selectColumnList);
            // 配置信息显示到页面
            if (null == databaseConfig) {
                return map;
            }
            String jsonShowColumn = databaseConfig.getShowColumn();
            if (StringUtils.isNotBlank(jsonShowColumn)) {
                Map<String, String> mapShowColumn = JSON.parseObject(jsonShowColumn, LinkedHashMap.class);
                if (!CollectionUtils.isEmpty(mapShowColumn)) {
                    List<String> listShowColumn = new ArrayList<>();
                    for (Map.Entry<String, String> entry : mapShowColumn.entrySet()) {
                        listShowColumn.add(entry.getKey());
                    }
                    map.put("listShowColumn", listShowColumn);
                }
            }
            //排序字段
            String strOrderColumn = databaseConfig.getOrderColumn();
            if (StringUtils.isNotBlank(strOrderColumn)) {
                String[] arrOrderColumn = strOrderColumn.split(",");
                if (null != arrOrderColumn && arrOrderColumn.length > 0) {
                    List<String> listOrderColumn = new ArrayList<>();
                    for (String colum : arrOrderColumn) {
                        if (StringUtils.isBlank(colum)) {
                            continue;
                        }
                        if (colum.endsWith("DESC")) {
                            listOrderColumn.add(colum.substring(0, colum.length() - 5) + "【DESC】");
                            continue;
                        }
                        if (colum.endsWith("ASC")) {
                            listOrderColumn.add(colum.substring(0, colum.length() - 4) + "【ASC】");
                            continue;
                        }
                        listOrderColumn.add(colum + "【ASC】");
                    }
                    map.put("listOrderColumn", listOrderColumn);
                }
            }
            //查询字段
            String jsonSelectColumn = databaseConfig.getSelectColumn();
            if (StringUtils.isNotBlank(jsonSelectColumn)) {
                Map<String, String> mapSelectColumn = JSON.parseObject(jsonSelectColumn, LinkedHashMap.class);
                if (!CollectionUtils.isEmpty(mapSelectColumn)) {
                    List<String> listSelectColumn = new ArrayList<>();
                    for (Map.Entry<String, String> entry : mapSelectColumn.entrySet()) {
                        if (StringUtils.isBlank(entry.getKey()) || StringUtils.isBlank(entry.getValue())) {
                            continue;
                        }
                        listSelectColumn.add(entry.getKey() + "【" + entry.getValue() + "】");
                    }
                    map.put("listSelectColumn", listSelectColumn);
                }
            }
            map.put("databaseConfig", databaseConfig);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            throw new BusinessException(ex.getMessage());
        }
        return map;
    }

    /**
     * 保存基础数据的配置管理
     *
     * @param databaseConfig
     * @throws Exception
     */
    public void saveDataBaseConfig(DatabaseConfig databaseConfig) throws Exception {
        if (null == databaseConfig || StringUtils.isBlank(databaseConfig.getCode())) {
            throw new BusinessException("获取配置信息失败，请稍后重试！");
        }
        QueryWrapper<Table> wrapper = new QueryWrapper<>();
        wrapper.eq("NAME", databaseConfig.getCode().toUpperCase().replace("RW_DB_", ""));
        Table table = tableService.getOne(wrapper);
        if (null == table || StringUtils.isBlank(table.getId())) {
            throw new BusinessException("获取基础数据表信息失败，请稍后重试！");
        }
        QueryWrapper<TableDetail> wrapperDetail = new QueryWrapper<>();
        wrapperDetail.eq("TABLE_ID", table.getId());
        List<TableDetail> listDetail = tableDetailService.list(wrapperDetail);
        // 获取库里所有字段
        if (CollectionUtils.isEmpty(listDetail)) {
            throw new BusinessException("获取基础配置表信息失败，请稍后重试！");
        }
        //显示字段
        if (StringUtils.isNotBlank(databaseConfig.getShowColumn())) {
            String[] arr = databaseConfig.getShowColumn().split(",");
            if (null != arr && arr.length > 0) {
                Map<String, String> map = new LinkedHashMap<>();
                for (String colum : arr) {
                    if (StringUtils.isBlank(colum)) {
                        continue;
                    }
                    if ("RW_DB_DATABASE_TYPE".equals(colum)) {
                        map.put(colum, "数据库类型");
                        continue;
                    }
                    for (TableDetail detail : listDetail) {
                        if (null == detail || !colum.equals(detail.getColumnName())) {
                            continue;
                        }
                        if (StringUtils.isBlank(detail.getColumnChineseName())) {
                            map.put(colum, colum);
                            break;
                        }
                        map.put(colum, detail.getColumnChineseName());
                        break;
                    }
                }
                if (!CollectionUtils.isEmpty(map)) {
                    databaseConfig.setShowColumn(JSONObject.toJSONString(map));
                }
            }
        }
        //排序字段  CLASS_ID【ASC】,CLASS_NAME【ASC】,KEY_ID【ASC】,KEY_SEQ【ASC】,CLASS_ENAME【ASC】,MEMO【ASC】
        if (StringUtils.isNotBlank(databaseConfig.getOrderColumn())) {
            String onlyColum = databaseConfig.getOrderColumn().replace("【", " ");
            onlyColum = onlyColum.replace("】", "");
            databaseConfig.setOrderColumn(onlyColum);
        }
        //查询字段   CLASS_ID【LIKE】,CLASS_NAME【LIKE】,CLASS_ENAME【LIKE】
        if (StringUtils.isNotBlank(databaseConfig.getSelectColumn())) {
            String[] arr = databaseConfig.getSelectColumn().split(",");
            if (null != arr && arr.length > 0) {
                Map<String, String> map = new LinkedHashMap<>();
                for (String colum : arr) {
                    if (StringUtils.isBlank(colum)) {
                        continue;
                    }
                    String[] arrColum = colum.split("【");
                    if (null != arrColum && arrColum.length == 2 && StringUtils.isNotBlank(arrColum[0]) && StringUtils.isNotBlank(arrColum[1])) {
                        map.put(arrColum[0].trim(), arrColum[1].replace("】", "").trim());
                    }
                }
                if (!CollectionUtils.isEmpty(map)) {
                    databaseConfig.setSelectColumn(JSONObject.toJSONString(map));
                }
            }
        }
        databaseConfig.setPrimaryKeyColumn("RW_DB_ID");
        // 新增
        if (StringUtils.isBlank(databaseConfig.getId())) {
            databaseConfig.setAddUser(redisCacheManager.getLoginUserInfo().getLoginId());
            databaseConfig.setAddTime(LocalDateTime.now());
            databaseConfig.setId(DateUtil.generateUUID());
            this.save(databaseConfig);
            return;
        }
        databaseConfig.setEditUser(redisCacheManager.getLoginUserInfo().getLoginId());
        databaseConfig.setEditTime(LocalDateTime.now());
        this.updateById(databaseConfig);
    }

}
